<template>
	<el-checkbox-group v-model="checkRoles">
		<el-checkbox v-for="item in roles" :label="item.RoleName" :value="item.RoleValue" />
	</el-checkbox-group>
	<hr>
	<el-button type="primary" @click="submitForm()">保存</el-button>
	<el-button @click="resetForm()">重置</el-button>
</template>

<script lang="ts" setup>
	import { ref, onMounted } from 'vue'
	import { ElNotification } from 'element-plus'

	import userroleapi from '../../api/userroleapi';
	import roleapi from '../../api/roleinfoapi';

	const props = defineProps({
		Id: Number,
	});

	const emit = defineEmits(['onSave'])

	const roles:any = ref([]);
	const checkRoles = ref<any>([])

	const getdata = () => {
		roleapi.QueryStatus({ RoleName: "", PageSize: 100, PageIndex: 1 }).then(res => {
			roles.value = res.data;
			console.log("roles=", roles.value);
		}).catch(err => {
			console.log("err=", err);
		})
	}

	const userrole = () => {
		userroleapi.userrole({ UserId: props.Id }).then(res => {
			if (res.code == 1) {
				checkRoles.value = [];
				res.data.forEach((item) => {
					checkRoles.value.push(item.RoleId)
				})
				console.log("checkRoles", checkRoles)
			}
		})
	}
	onMounted(() => {
		getdata();
		userrole();
	})

	const submitForm = () => {
		
		var data = { UserId: props.Id, RoleIds: checkRoles.value };
		console.log("data", data)
		
		userroleapi.AddUserRole(data).then(res => {
			if (res.code == 1) {
				ElNotification({
					title: 'Success',
					message: '授权成功',
					type: 'success',
					duration: 800,
					onClose: () => {
						emit("onSave", true)
					}
				})
			} else {
				ElNotification({
					title: 'Error',
					message: '失败',
					type: 'error',
					duration: 800,
				})
			}
		})
	}
	const resetForm = () => {
		userrole();
	}
</script>